package controllers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
)

func SequenceController(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
	w.Header().Set("content-type", "application/json")
	type Res struct {
		Status         int
		Info           string
		SequenceNumber string
	}
	dir, error := os.OpenFile("/sys/devices/w1_bus_master1/", os.O_RDONLY, os.ModeDir)
	if error != nil {
		defer dir.Close()
		fmt.Println(error.Error())
		return
	}
	// fileinfo, _ := dir.Stat()
	// fmt.Println(fileinfo.IsDir())
	names, _ := dir.Readdir(-1)
	var file string
	for _, name := range names {
		if name.IsDir() {
			if strings.Contains(name.Name(), "28-") {
				// fmt.Println(name.Name(), "目录")
				file = name.Name()
			}
		}
	}
	var m Res
	m.Status = 0
	m.Info = "ok"
	var sequence_number string = strings.ToUpper(string(file[3:]))
	m.SequenceNumber = sequence_number
	bytes, _ := json.Marshal(m)
	w.WriteHeader(http.StatusOK)
	w.Write(bytes)
}
